<?php
class Core_Controller_Action_Ajax extends Zend_Controller_Action {
	const LOGIC_ERROR = 1342;
	protected $_jsonResponse = array ();
	protected $_error;
	protected $_is_rendered = false;
	
	public function preDispatch() {
		$this->_helper->layout->disableLayout ();
		$this->_helper->viewRenderer->setNoRender ( true );
	}
	public function dispatch($action) {
		// Notify helpers of action preDispatch state
		$this->_helper->notifyPreDispatch ();
		
		$this->preDispatch ();
		if ($this->getRequest ()->isDispatched ()) {
			if (null === $this->_classMethods) {
				$this->_classMethods = get_class_methods ( $this );
			}
			
			// preDispatch() didn't change the action, so we can continue
			if ($this->getInvokeArg ( 'useCaseSensitiveActions' ) || in_array ( $action, $this->_classMethods )) {
				if ($this->getInvokeArg ( 'useCaseSensitiveActions' )) {
					trigger_error ( 'Using case sensitive actions without word separators is deprecated; please do not rely on this "feature"' );
				}
				try {
					$this->$action ();
				} catch ( Exception $e ) {
					if ($e->getCode () != self::LOGIC_ERROR)
						throw $e;
					$this->_jsonRender ( $e->getMessage () );
				}
			} else {
				$this->__call ( $action, array () );
			}
			$this->postDispatch ();
		}
		
		// whats actually important here is that this action controller is
		// shutting down, regardless of dispatching; notify the helpers of this
		// state
		$this->_helper->notifyPostDispatch ();
	}
	
	public function error($msg = null, $code = null) {
		$this->_error = $code;
		throw new Exception ( $msg, self::LOGIC_ERROR );
	}
	public function push($key, $val) {
		$this->_jsonResponse [$key] = $val;
	}
	public function get($key) {
		return $this->_jsonResponse [$key];
	}
	
	protected function _jsonRender($error = null) {
		$this->_is_rendered = true;
		print json_encode ( array ("status" => is_null ( $error ) ? true : false, "msg" => is_null ( $error ) ? null : $error, "data" => $this->_jsonResponse ) );
	}
	
	public function postDispatch() {
		if (! $this->_is_rendered)
			$this->_jsonRender ();
	}
}